import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from flask import send_from_directory

# 文件存放路劲
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'media')

# 文件上传格式
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__ , template_folder="../templates")
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 文件最大大小限制
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

# 校验文件格式
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upfile', methods=['GET', 'POST'])
def up_file():
    if request.method == 'GET':
        return render_template('upfile.html')
    if request.method == 'POST':
        title = request.form.get('title')  # form 获取表单参数
        file = request.files.get('file')  # file 或取文件参数
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  # 校验文件名称合法
            print(filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return {
                'msg': 'success',
                'url': f'/images/{filename}/',
            }
        else:
            return {
                'msg': '文件格式不支持'
            }

@app.route('/images/<filename>/')
def get_image(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)

if __name__ == '__main__':
    app.run()